<?php

/**
* -------------------------------------------------------------------------------------------------------------------
* @abstract   Handles the CRUD operations for Admin and other methods
* @package    Kiropedic
* @subpackage Controllers
* @author     Darwing Hernández - darwing.her69@gmail.com
* -------------------------------------------------------------------------------------------------------------------
*/

class AdminController extends BaseController
{
  /**
  * ---------------------------------------------------------------------------------------------------------------
  * ATTRIBUTES AND CONSTANTS
  * ---------------------------------------------------------------------------------------------------------------
  */
  
  public $restful = true;

  /**
  * ---------------------------------------------------------------------------------------------------------------
  * VIEWS
  * ---------------------------------------------------------------------------------------------------------------
  */

  /**
  * @abstract Shows the index page
  * @return   View
  * @access   public  
  */
  public function welcome()
  {
    // If user is not authenticated, redirects to login view
    if(!Auth::guest()) return Redirect::to('admin');
    return View::make('admin/login');
  }

  /**
  * @abstract  Shows the list views according to what list is wanted to be displayed
  * @param     string   -   the list to be listed
  * @return    View
  * @access    public 
  */
  public function listing($list)
  {
    switch($list)
    {
      case "listadmin": 
        $admins = Admin::paginate(10, array('adm_code', 'adm_login', 'adm_name', 'adm_email', 'adm_active'));
        return  View::make('admin.admin.listadmin')->with('admins', $admins)->with('title', 'Administradores')->with('active', 1);
      break;
      case "listuser":  
        $users = User::paginate(10, array('usr_code','usr_name', 'usr_rifci', 'usr_cellphone', 'usr_status', 'usr_active'));
        return  View::make('admin.user.listuser')->with('users', $users)->with('title', 'Clientes')->with('active', 2);
      break;
      case "listoper":  
        $operators = Operator::paginate(10, array('ope_code', 'ope_login', 'ope_name', 'ope_rifci', 'ope_phone', 'ope_email', 'ope_active'));
        return  View::make('admin.operator.listoper')->with('operators', $operators)->with('title', 'Operadores')->with('active', 3);
      break;
      case "listserv":  
        $services = Service::paginate(10, array('srv_code','srv_name', 'srv_codctrl', 'srv_priceunit', 'srv_type', 'srv_active'));
        return  View::make('admin.service.listserv')->with('services', $services)->with('title', 'Servicios')->with('active', 4);
      break;
      case "listprod":
        $products = Product::paginate(10, array('pro_code','pro_name', 'pro_codctrl', 'pro_priceunit', 'pro_active'));
        return  View::make('admin.product.listprod')->with('products', $products)->with('title', 'Productos')->with('active', 5);
      break;
      default: return Response::view('errors.404', array(), 404);  break;
    }
  }

  /**
  * @abstract  Shows the create views according to what model is wanted to be created
  * @param     string   -   the model to be created
  * @return    View
  * @access    public 
  */
  public function creating($model)
  {
    switch($model)
    {
      case "admin": return View::make('admin.admin.createAdmin')->with('title', 'Crear Nuevo Administrador')->with('active', 1);
      break;
      case "user":  return View::make('admin.user.createUser')->with('title', 'Crear Nuevo Cliente')->with('active', 2);
      break;
      case "oper":  return View::make('admin.operator.createOper')->with('title', 'Crear Nuevo Operador')->with('active', 3);     
      break;
      case "serv":  return View::make('admin.service.createServ')->with('title', 'Crear Nuevo Servicio')->with('active', 4);
      break;
      case "prod":  return View::make('admin.product.createProd')->with('title', 'Crear Nuevo Producto')->with('active', 5);
      break;
      default: return Response::view('errors.404', array(), 404); break;
    }
  }

  /**
  * ----------------------------------------------------------------------------------------------------------------
  * CRUD OPERATIONS
  * ----------------------------------------------------------------------------------------------------------------
  */

  /**
  * CREATE Operation
  * @abstract creates a new admin record
  * @return   View
  * @access   public
  */
  public function create()
  {
    $index  = array('login', 'email');
    $values = array('unique:admin_adm,adm_login', 'unique:admin_adm,adm_email');

    // Validates the submitted input
    if (!$this->validate(Input::all(), CREATE_ADMIN, $index, $values)) 
      return  Redirect::to('admin/create/admin')->with('notification', 'register_add_warning')
                      ->with('opt', 'El administrador ')
                      ->withErrors($this->validation)
                      ->withInput();

    $admin =  Admin::create(array(
      'adm_login'    => Input::get('login'),
      'adm_name'     => Input::get('nombre'),
      'adm_email'    => Input::get('email'),
      'adm_password' => Hash::make(Input::get('password')),
      'adm_active'   => Input::get('active') == "on"? 1: 0
    ));

    // Redirects to the same page form if user specified add more registers
    if(Input::get('again') == "on")
      return Redirect::to('admin/create/admin')->with('notification', "register_add_success")->with('opt', 'El administrador ');
    else
      return Redirect::to('admin/list/listadmin')->with('notification', "register_add_success")->with('opt', 'El administrador ');
  }

  /**
  * READ Operation
  * @abstract  Reads a record by id and shows the related data
  * @param     int - record ID
  * @return    View
  * @access    public
  */
  public function view($id)
  {
    $admin = Admin::select('adm_code', 'adm_login', 'adm_name', 'adm_email', 'adm_active')->find($id);

    if(!$admin) return Redirect::to('admin/list/listadmin')->with('notification', 'not_allowed');

    return  View::make('admin.admin.editAdmin')
                ->with('title', 'Editar Administrador')
                ->with('admin',  $admin)
                ->with('active', 1);
  }

  /**
  * READ Operation
  * @abstract  Reads a record by id and shows the related data (only to change password)
  * @param     int - record ID
  * @return    View
  * @access    public
  */
  public function viewchangepass($id)
  {
    $admin = Admin::select('adm_code', 'adm_login')->find($id);

    if(!$admin) return Redirect::to('admin/list/listadmin');

    return  View::make('admin.admin.changepass')
                ->with('title', 'Cambiar Contraseña de '. $admin->adm_login)
                ->with('admin',  $admin)
                ->with('active', 1);
  }

  /**
  * UPDATE Operation
  * @abstract  updates a record by id
  * @param     int - record ID
  * @return    View
  * @access    public
  */
  public function update($id)
  {
    $index  = array('login', 'email');
    $values = array('unique:admin_adm,adm_login,'.$id.',adm_code', 'unique:admin_adm,adm_email,'.$id.',adm_code');

    // Validates if data input submitted is valid
    if (!$this->validate(Input::all(), UPDATE_ADMIN, $index, $values)) 
      return  Redirect::to('admin/viewAdmin/'.$id)->with('notification', "register_edit_warning")->withErrors($this->validation);

    $admin              = Admin::find($id);
    $admin->adm_login   = Input::get('login');
    $admin->adm_name    = Input::get('nombre');
    $admin->adm_email   = Input::get('email');
    $admin->adm_active  = Input::get('active') == "on"? 1: 0;
    $admin->save();     // Saves the current model

    return  Redirect::to('admin/viewAdmin/'.$id)->with('notification', "register_edit_success");
  }

  /**
  * UPDATE Operation
  * @abstract  updates a record by id (change password)
  * @param     int - record ID
  * @return    View
  * @access    public
  */
  public function changepass($id)
  {
    // Validates if data input submitted is valid
    if (!$this->validate(Input::all(), CHANGE_PASS)) 
      return  Redirect::to('admin/changepass/'.$id)->with('notification', "admin_changepassw_warning")->withErrors($this->validation);

      $admin               = Admin::find($id);
      $admin->adm_password = Hash::make(Input::get('password'));
      $admin->save();      // Saves the current model

    return  Redirect::to('admin/list/listadmin')->with('notification', 'admin_changepassw_success');
  }

  /**
  * DELETE Operation
  * @abstract deletes records by specified IDs
  * @access   public
  */
  public function delete()
  {
    $dbname = Input::get('fec1e92a71');                         // Table from deleting
    $keys   = preg_split("/[\s,]+/", Input::get('deletereg'));  // IDs of records to delete

    // Calls the according methond to delete from the table
    switch ($dbname) 
    {
      case 'user_usr':     return UserController::delete($keys);     break;
      case 'admin_adm':    break;
      case 'operator_ope': return OperatorController::delete($keys); break;
      case 'service_srv':  return ServiceController::delete($keys);  break;
      case 'product_pro':  return ProductController::delete($keys);  break;
    }
  }

  /**
  * ----------------------------------------------------------------------------------------------------------------
  * OTHERS METHODS/ACTIONS AND STUFF
  * ----------------------------------------------------------------------------------------------------------------
  */

  /**
  * @abstract Attempts to login an admin user
  * @return   View
  * @access   public  
  */
  public function login()
  {
      $userdata = array(
        'adm_login' => Input::get('username'),
        'password'  => Input::get('password')
      );

      // Attempts to authenticate
      if (Auth::attempt($userdata))
      {
        Auth::login(Auth::user());
        return  Redirect::to('admin');
      }else return Redirect::to('login')->with('login_errors', true);
  }

  /**
  * @abstract  Calls the create method of the model specified by the name
  * @param     string   - the model name
  * @return    View
  * @access    public 
  */
  public function _create($model)
  {
    switch($model)
    {
      case "admin":  return Redirect::action('AdminController@create');            break;
      case "user":   return Redirect::action('UserController@registerUserAdmin');  break;
      case "oper":   return Redirect::action('OperatorController@register');       break;
      case "serv":   return Redirect::action('ServiceController@register');        break;
      case "prod":   return Redirect::action('ProductController@register');        break;
      default:       return Response::view('errors.404', array(), 404);            break;
    }
  }

  /**
  * @abstract  Calls the editing method of the model specified by the name and displays the view
  * @param     string   - the model name
  * @param     int  - the record ID
  * @return    View
  * @access    public 
  */
  public function editing($model, $id)
  {
    switch($model)
    {
      case "admin":  return Redirect::action('AdminController@view', $id);     break;
      case "user":   return Redirect::action('UserController@view', $id);      break;
      case "oper":   return Redirect::action('OperatorController@view', $id);  break;
      case "serv":   return Redirect::action('ServiceController@view', $id);   break;
      case "prod":   return Redirect::action('ProductController@view', $id);   break;
      default:       return Response::view('errors.404', array(), 404);        break;
    }
  }

  /**
  * @abstract  Calls the edit method of the model specified by the name
  * @param     string   - the model name
  * @param     int  - the record ID
  * @return    View
  * @access    public 
  */
  public function _edit($model, $id)
  {
    switch($model)
    {
      case "admin":  return Redirect::action('AdminController@update', $id);     break;
      case "user":   return Redirect::action('UserController@update', $id);      break;
      case "oper":   return Redirect::action('OperatorController@update', $id);  break;
      case "serv":   return Redirect::action('ServiceController@update', $id);   break;
      case "prod":   return Redirect::action('ProductController@update', $id);   break;
      default:       return Response::view('errors.404', array(), 404);          break;
    }
  }
}